<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class TargetService
{
    // 列表
    public static function index($data)
    {
//        return 123;
        $limit = isset($data['limit']) ? ($data['limit']/8) : 1;
        $page = isset($data['page']) ? $data['page'] : 1;
        //分页查询
        $target = \app\admin\model\Target::field('target_id,user_id,start_time,end_time,lead,appointment,visit,student_enrollment,student_retention,contract_number,contract_amount,cashin')
            ->paginate($limit);
        if($target){
            $list = [];
            foreach ($target as $key => $value) {
                $saff = \app\admin\model\User::field('id,english_name,group_id')->where(['id'=>$value['user_id']])->find();
                if($saff){
                    $role  = \app\admin\model\UserGroup::field('name')->where(['id'=>$saff['group_id']])->find();
                }else{
                    continue;
                }
                if($value['lead'] >= 0){
                    $list[] = [
                        'target_id' => $value['target_id'],
                        'item_name' => 'Lead',
                        'target' => $value['lead'],
                        'start_date' => $value['start_time'],
                        'end_date' => $value['end_time'],
                        'role' => $role['name'],
                        'saff_name' => $saff['english_name'],
                    ];
                }
                if($value['appointment'] >= 0){
                    $list[] = [
                        'target_id' => $value['target_id'],
                        'item_name' => 'Appointment',
                        'target' => $value['appointment'],
                        'start_date' => $value['start_time'],
                        'end_date' => $value['end_time'],
                        'role' => $role['name'],
                        'saff_name' => $saff['english_name'],
                    ];
                }
                if($value['visit'] >= 0){
                    $list[] = [
                        'target_id' => $value['target_id'],
                        'item_name' => 'Visit',
                        'target' => $value['visit'],
                        'start_date' => $value['start_time'],
                        'end_date' => $value['end_time'],
                        'role' => $role['name'],
                        'saff_name' => $saff['english_name'],
                    ];
                }
                if($value['student_enrollment'] >= 0){
                    $list[] = [
                        'target_id' => $value['target_id'],
                        'item_name' => 'Student Enrollment',
                        'target' => $value['student_enrollment'],
                        'start_date' => $value['start_time'],
                        'end_date' => $value['end_time'],
                        'role' => $role['name'],
                        'saff_name' => $saff['english_name'],
                    ];
                }
                if($value['student_retention'] >= 0){
                    $list[] = [
                        'target_id' => $value['target_id'],
                        'item_name' => 'Student Retention',
                        'target' => $value['student_retention'],
                        'start_date' => $value['start_time'],
                        'end_date' => $value['end_time'],
                        'role' => $role['name'],
                        'saff_name' => $saff['english_name'],
                    ];
                }
                if($value['contract_number'] >= 0){
                    $list[] = [
                        'target_id' => $value['target_id'],
                        'item_name' => 'Contract Number',
                        'target' => $value['contract_number'],
                        'start_date' => $value['start_time'],
                        'end_date' => $value['end_time'],
                        'role' => $role['name'],
                        'saff_name' => $saff['english_name'],
                    ];
                }
                if($value['contract_amount'] >= 0){
                    $list[] = [
                        'target_id' => $value['target_id'],
                        'item_name' => 'Contract Amount',
                        'target' => $value['contract_amount'],
                        'start_date' => $value['start_time'],
                        'end_date' => $value['end_time'],
                        'role' => $role['name'],
                        'saff_name' => $saff['english_name'],
                    ];
                }
                if($value['cashin'] >= 0){
                    $list[] = [
                        'target_id' => $value['target_id'],
                        'item_name' => 'Cash In',
                        'target' => $value['cashin'],
                        'start_date' => $value['start_time'],
                        'end_date' => $value['end_time'],
                        'role' => $role['name'],
                        'saff_name' => $saff['english_name'],
                    ];
                }
            }
        }
        $number = $target = \app\admin\model\Target::count();
        $total = $number * 8;
        $last_page = ceil($total / 8);

        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>['total'=>$total,'per_page'=>8,'current_page'=>$page,'last_page'=>$last_page,'data'=>$list]];
    }


    // 保存
    public static function save($data)
    {
        // 验证规则
        $validate = new Validate([
            'target_id' => 'number',
            'country' => 'require',
            'region' => 'require',
            'studio_id' => 'require',
            'currency' => 'require',
            'role_id' => 'require',
            'saff_id' => 'require',
            'start_time' => 'require|dateFormat:Y-m-d',
            'end_time' => 'require|dateFormat:Y-m-d',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 验证日期逻辑
        if (strtotime($data['end_time']) <= strtotime($data['start_time'])) {
            return ['code'=>400, 'msg'=>'End time must be later than start time', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 准备保存的数据 (添加基本XSS防护)
        $saveData = [
            'country' => htmlspecialchars($data['country'] ?? '', ENT_QUOTES),
            'region' => htmlspecialchars($data['region'] ?? '', ENT_QUOTES),
            'studio_id' => $data['studio_id'],
            'currency' => htmlspecialchars($data['currency'] ?? '', ENT_QUOTES),
            'user_id' => $data['saff_id'], // user_id = saff_id
            'start_time' => $data['start_time'],
            'end_time' => $data['end_time'],
            'lead' => $data['lead'] ?? null,
            'appointment' => $data['appointment'] ?? null,
            'visit' => $data['visit'] ?? null,
            'student_enrollment' => $data['student_enrollment'] ?? null,
            'student_retention' => $data['student_retention'] ?? null,
            'contract_number' => $data['contract_number'] ?? null,
            'contract_amount' => $data['contract_amount'] ?? null,
            'cashin' => $data['cashin'] ?? null,
            'marketing_cashin' => $data['marketing_cashin'] ?? null,
            'referral_cashin' => $data['referral_cashin'] ?? null,
            'renewal_cashin' => $data['renewal_cashin'] ?? null,
        ];

        try {
            // 启用事务
            Db::startTrans();

            if (isset($data['target_id']) && $data['target_id']) {
                // 更新已有记录
                $result = \app\admin\model\Target::update($saveData, ['target_id' => $data['target_id']]);
                $message = 'Update successful';
            } else {
                // 新增记录
                $result = \app\admin\model\Target::create($saveData);
                $message = 'Create successful';
            }

            if ($result) {
                Db::commit();
                return ['code'=>200, 'msg'=>$message, 'state'=>'OK', 'data'=>$result];
            } else {
                Db::rollback();
                return ['code'=>400, 'msg'=>'Operation failed', 'state'=>'FAILED', 'data'=>null];
            }
        } catch (\Exception $e) {
            Db::rollback();
            // 生产环境应使用通用错误信息
            return ['code'=>400, 'msg' => 'Database error: ' . $e->getMessage(),  'state'=>'DATABASE_ERROR', 'data'=>null];
        }
    }

    // 详情
    public static function detail($data)
    {
        $validate = new Validate([
            'target_id' => 'number',
        ]);
        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }
        $result = \app\admin\model\Target::where('target_id', $data['target_id'])->find();
        $user = \app\admin\model\User::where('id', $result['user_id'])->find();
        $result['staff_id'] = $user['id'];
        $result['role_id'] = $user['group_id'];

        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
    }


    // 删除
    public static function del($data)
    {

        $validate = new Validate([
            'target_id' => 'number',
        ]);
        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }
        $result = \app\admin\model\Target::where('target_id', $data['target_id'])->delete();
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
    }




}
